package cn.e3mall.search.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.e3mall.common.pojo.SearchItem;
import cn.e3mall.common.pojo.SearchResult;

/**
 * @description 商品搜索的Dao层
 * @author JiangBin
 * @date 2018年3月12日 下午10:32:58
 * @version 1.0.0 @
 */
@Repository
public class SearchDao {

	@Autowired
	private SolrServer slorServer;

	public SearchResult search(SolrQuery solrQuery) throws SolrServerException {
		// 根据查询条件查询索引库
		QueryResponse queryResponse = slorServer.query(solrQuery);
		// 获取查询结果总记录数
		SolrDocumentList solrDocumentList = queryResponse.getResults();
		long numFound = solrDocumentList.getNumFound();
		// 创建一个返回结果
		SearchResult result = new SearchResult();
		result.setRecourdCount((int) numFound);

		// 创建一个商品列表对象
		List<SearchItem> itemList = new ArrayList<>();
		// 获取商品列表
		// 获取高亮的结果
		Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
		for (SolrDocument solrDocument : solrDocumentList) {
			// 获取商品
			SearchItem searchItem = new SearchItem();
			searchItem.setCategroy_name((String) solrDocument.get("item_category_name"));
			searchItem.setId((String) solrDocument.get("id"));
			searchItem.setImage((String) solrDocument.get("item_image"));
			searchItem.setPrice((Long) solrDocument.get("item_price"));
			searchItem.setSell_ponit((String) solrDocument.get("item_sell_point"));

			// 获取高亮结果
			List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
			String itemTitle = "";
			if (list != null && list.size() > 0) {
				itemTitle = list.get(0);
			} else {
				itemTitle = (String) solrDocument.get("item_title");
			}
			searchItem.setTitle(itemTitle);
			itemList.add(searchItem);
		}
		// 把列表添加到返回结果对象中
		result.setItemList(itemList);
		return result;
	}
}
